package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;

    @Autowired
    private ICarPackageAuditService carPackageAuditService;

    @Autowired
    private IBpmnInfoService bpmnInfoService;

    @Autowired
    private RuntimeService runtimeService;


    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        // 判断是否为套餐,如果是套餐这把审核状态设置为初始化
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())) {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        } else {
            // 若不是则设置审核状态为无需审核
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        // 设置默认的销售状态
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        // 创建存储时间
        serviceItem.setCreateTime(new Date());
        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        /**
         * 1.已上架,不能直接编辑,需要下架后才能进行编辑
         * 2.未上架,但是是套餐且处于审核状态,这时候也不能进行编辑
         * 如果未上架,审核通过了,再重新编辑    把审核状态修改为初始化
         */
        ServiceItem st = this.get(serviceItem.getId());
        // 上架状态不能直接编辑
        if (ServiceItem.SALESTATUS_ON.equals(st.getSaleStatus())) {
            throw new BusinessException("该选项处于上架中,无法进行编辑");
        }
        // 未上架 是套餐且没有审核通过,不能进行修改
        if (ServiceItem.CARPACKAGE_YES.equals(st.getCarPackage()) &&
                ServiceItem.AUDITSTATUS_AUDITING.equals(st.getAuditStatus())) {
            throw new BusinessException("该选项正处于审核中状态,无法进行编辑");
        }
        // 如果未上架但 是套餐审核通过了,再重新编辑    把审核状态修改为初始化
        if (ServiceItem.CARPACKAGE_YES.equals(st.getCarPackage()) &&
                ServiceItem.AUDITSTATUS_APPROVED.equals(st.getAuditStatus())) {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        } else {
            serviceItem.setAuditStatus(st.getAuditStatus());
        }
        // 将上架状态重置为下架状态
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    @Override
    public void saleOn(Long id) {
        /**
         * 数据合理化校验
         * 数据处于下架状态
         * 非套餐=>直接上架
         * 套餐=>处于审核通过的状态才可以进行上架
         * 把状态saleStatus修改为上架状态
         */
        ServiceItem serviceItem = this.get(id);
        if (ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())) {
            throw new BusinessException("该项处于上架状态");
        }
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage()) && !ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())) {
            throw new BusinessException("套餐处于审核中的状态");
        }

        serviceItemMapper.changeSaleStatus(id, ServiceItem.SALESTATUS_ON);
    }

    @Override
    public void saleOff(Long id) {
        serviceItemMapper.changeSaleStatus(id, ServiceItem.SALESTATUS_OFF);
    }


    @Override
    public void startAudit(Long id, Long bpmnInfoId, Long director, Long finance, String info) {

        // 合理性校验
        ServiceItem serviceItem = this.get(id);
        if (ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())
                || ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage())
                || ServiceItem.AUDITSTATUS_AUDITING.equals(serviceItem.getAuditStatus())
                || ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())
                || ServiceItem.AUDITSTATUS_NO_REQUIRED.equals(serviceItem.getAuditStatus())) {
            throw new BusinessException("非法的操作");
        }

        // 修改服务状态,修改为审核中
        serviceItemMapper.changeAuditStatus(id, ServiceItem.AUDITSTATUS_AUDITING);

        CarPackageAudit carPackageAudit = new CarPackageAudit();
        carPackageAudit.setServiceItemId(id);                                   // 服务单项Id
        carPackageAudit.setServiceItemName(serviceItem.getName());              // 服务单项名称
        carPackageAudit.setServiceItemInfo(serviceItem.getInfo());              // 服务单项备注信息
        carPackageAudit.setServiceItemPrice(serviceItem.getDiscountPrice());    // 服务单项价格
        carPackageAudit.setCreator(ShiroUtils.getUser().getUserName());         // 创建人当前登录用户
        carPackageAudit.setAuditorId(director);                                 // 审核人
        carPackageAudit.setBpmnInfoId(bpmnInfoId);                              // 流程定义Id
        carPackageAudit.setInfo(info);                                          // 备注信息
        carPackageAudit.setCreateTime(new Date());                              // 创建时间
        // 保存审核对象
        carPackageAuditService.save(carPackageAudit);

        // 启动流程
        Map<String, Object> map = new HashMap<>();

            map.put("director", director);

        if (finance != null) {
            map.put("finance", finance);
        }
        map.put("discountPrice", serviceItem.getDiscountPrice().longValue());
        // 获取BpmnInfo对象
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);
        // 获取流程实例对象
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(bpmnInfo.getActProcessKey(), String.valueOf(carPackageAudit.getId()), map);

        // 审核对象关联流程实例Id
        carPackageAudit.setInstanceId(processInstance.getId());
        carPackageAuditService.update(carPackageAudit);

    }


    @Override
    public void changeAuditStatus(Long serviceItemId, Integer status) {
        serviceItemMapper.changeAuditStatus(serviceItemId, status);
    }
}
